//
//  AppDelegate.m
//  ShortcutPrj
//
//  Created by ShaoHong Wen on 8/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <unistd.h>
AppDelegate *_appDelegate;
@implementation AppDelegate

@synthesize window = _window,responseData=_responseData;
- (void)dealloc
{
    [_window release];
    [_responseData release];
    [super dealloc];
}
-(void)onResponseData:(CFWriteStreamRef)stream type:(CFStreamEventType)type client:(SocketClient *)client{
//    NSError *error=nil;
//    NSString* html=[NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"data" ofType:@"html"] encoding:NSUTF8StringEncoding error:&error];
//    if(error){
//        NSLog(@"read html data error:%@",[error debugDescription]);
//        return;
//    }
    if(!_responseData || [_responseData length]==0){
        return;
    }
    NSMutableString *res=[[NSMutableString alloc]init];
    [res appendString:@"HTTP/1.1 200 OK\r\n"];
    [res appendString:@"Cache-Control:no-cache\r\n"];
    [res appendString:@"Expires:0\r\n"];
    [res appendString:@"Pragma:no-cache\r\n"];
    [res appendString:@"Connection:Keep-Alive\r\n"];
    [res appendString:@"Content-Type:text/html;charset=UTF-8\r\n"];
    [res appendString:@"Connection:Keep-Alive\r\n"];
    [res appendString:@"Server:ShortcutServer\r\n"];
    [res appendFormat:@"Content-Length:%d\r\n\n",[_responseData length]];
    [res appendFormat:@"%@",_responseData];
    const char* data=[res UTF8String];
    CFWriteStreamWrite(stream, (unsigned char*)data, strlen(data));
    [res release];
    [client close];
}
-(void)onReceiveData:(CFReadStreamRef)stream type:(CFStreamEventType)type client:(SocketClient *)client{
    unsigned char buf[1024];
    CFIndex idx=CFReadStreamRead(stream, buf, 1024*100);
    buf[idx]=0;
    NSLog(@"receive data len:%d,data:%s",(int)idx,buf);
}
-(void)onAcceptConnect:(SocketClient *)client builder:(SocketBuilder *)builder{
    client.delegate=self;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    _appDelegate=self;
    return YES;
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    builder=[[SocketBuilder alloc]initWithPort:60000];
    if(![builder isValid]){
        NSLog(@"initial socket builder faild.");
        [builder release];
        builder=nil;
        return;
    }
    builder.delegate=self;
    [builder addToLoop];
    [application beginBackgroundTaskWithExpirationHandler:^{
        NSLog(@".............................");
        //CFRunLoopRun();
    }];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    if(builder){
        [builder release];
        builder=nil;
    }
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
+(AppDelegate*)appDelegate{
    return _appDelegate;
}
@end
